<?php
namespace App\Http\Controllers\www;

use App\Http\Controllers\Weixin\WeixinServiceController;
use Carbon\Carbon;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use DB;
use App\Models\V1\Active666Model;
use EasyWeChat\Payment\Order;
use App\Models\V1\RegionModel;
use Intervention\Image\Facades\Image;
use App\Models\V1\OrderProcessTemplateModel;
use App\Jobs\BaiduYuyin666Job;
use App\Common\Http;


class ZhongchouAdminController extends Controller{



    public function check_login(Request $request)
    {
        $name   = $request->session()->get('adminName');
        if(empty($name))
        {
            header('Location:/www/zhongchouAdmin/login');
            exit;
        }
    }


    public function add_type(Request $request)
    {
        $typeFile   = "";
        $typeId     = $request->input('typeId');
        $data   = ['type_name'=>$request->input('typeName')];

        if($request->file('typeFile'))
        {
            $path   = 'www/zc666/upload/';
            $typeFile = $request->file('typeFile')->store($path, 'public');
            $data['img']    = $typeFile;
        }

        if($typeId == 0 && $typeFile == "")
        {
            $data['img']    = "";
        }
        if($typeId > 0)
        {
            DB::table('666_type')->where('type_id',$typeId)->update($data);

        }else{

            DB::table('666_type')->insert($data);

        }
        return response()->redirectTo('www/zhongchouAdmin/index');
    }


    /**
     * 项目总览界面
     * */
    public function index(Request $request)
    {
        $this->check_login($request);

        $types  = DB::table('666_type')->paginate(15);

        $data   = [
            'admin' => $request->session()->get('adminName'),
            'time'  => date('Y/m/d'),
            'types' => $types
        ];

        return view('www/zc-admin/index',$data);
    }



    /**
     * 登录
     * */
    public function login()
    {
        return view('www/zc-admin/login');
    }


    /**
     * 登录动作
     * */
    public function login_action(Request $request)
    {
        if($request->name != "shidao" || $request->pass != "shidao2018")
        {
            return apiData()->notice("登录失败");
        }
        $request->session()->set('adminName',$request->input('name'));
        return response()->redirectTo('www/zhongchouAdmin/index');
    }



    /**
     * 退出
     * */
    public function login_out(Request $request)
    {

        $request->session()->remove('adminName');

        return response()->redirectTo('/www/zhongchouAdmin/login');
    }


    public function total_order(Request $request)
    {
        $this->check_login($request);
        $typeId     = $request->input('typeId');
        $wxname     = trim($request->input('wxname',''));
        $title      = trim($request->input('title',''));
        $id         = trim($request->input('id',0));
        $status     = trim($request->input('status','-1'));
        $mobile     = trim($request->input('mobile',''));
        $sort       = $request->input('sort','time');
        $activityId = $request->input('activityId',0);
        $showchild  = $request->input('showchild',0);

        $activities = DB::table('666_activity')->select('activity_id','title')->where('type_id',$typeId)->get();
        $orders     = DB::table('666_order as a')
            ->leftJoin('666_activity as b','b.activity_id','=','a.activity_id')
            ->where('b.delete_at')
            ->where('a.deleted_at')
            ->where('b.type_id',$typeId);

        $orders = $orders->where(function($db) use ($wxname,$title,$mobile,$status,$activityId) {

                if($title)
                {
                    $db->orWhere('b.title','like',"%{$title}%");
                }

                if($wxname)
                {
                    $db->orWhere('a.wx_name','like',"%{$wxname}%");
                }


                if($mobile){
                    $db->orWhere('a.mobile','like',"%{$mobile}%");
                }
        });

        if($activityId > 0)
        {
            $orders->where('a.activity_id','=',$activityId);
        }

        if($sort == 'time')
        {
            $orders->orderBy('a.id','desc');
        }else{
            $orders->orderBy('a.raised_money','desc');
        }


        $handStatus = $request->input('handStatus','-1');
        if($handStatus == "1")
        {
            $orders->where('a.hand_status',1);

        }elseif($handStatus == "0") {

            $orders->where('a.hand_status',0);
        }

        $orders = $orders->select("a.*",'b.title','b.money','b.begin_time','b.end_time')->paginate(10);



        foreach($orders as $order)
        {

            if($showchild == 1)
            {
                //获得所有子订单
                $count = DB::table('666_order')->where('parent_id',$order->id)->where('deleted_at')->count();


                //所有已完成的子订单
                $finishChild = DB::table('666_order as a')->leftJoin('666_activity as b','b.activity_id','=','a.activity_id')
                    ->where('a.parent_id',$order->id)
                    ->where('a.raised_money',">=",DB::raw('b.money'))
                    ->count();

                //所有子订单
                $allNum     = DB::table('666_order')->whereRaw(DB::raw('find_in_set("'.$order->id.'",id_tree)'))->count();


            } else {

                $count = 0;
                $finishChild = 0;
                $allNum     = 0;
            }

            $order->all_num             = $allNum;
            $order->child_num           = $count;
            $order->child_finished_num  = $finishChild;
            $order->begin_time          = str_replace("-","/",substr($order->begin_time,0,11));
            $order->end_time            = str_replace("-","/",substr($order->end_time,0,11));
        }

        $numbers = $this->get_order_type_numbers($typeId);

        //获取总的数据

        $data       = [
            'orders'    => $orders,
            'typeId'    => $typeId,
            'total'     => $numbers['total'],
            'finish'    => $numbers['finish'],
            'activitys' => $activities
        ];

        return view('www/zc-admin/total_order',$data);
    }


    public function child_order(Request $request)
    {

        $this->check_login($request);
        $type       = $request->input('type');
        $parentId   = $request->input('parentId');
        $typeId     = $request->input('typeId');


        $orders     = DB::table('666_order as a')
            ->leftJoin('666_activity as b','b.activity_id','=','a.activity_id')
            ->where('b.delete_at')
            ->where('a.deleted_at');

        if($type == 1)
        {
            $orders = $orders->where('a.parent_id',$parentId)->where('a.raised_money',">=",DB::raw('b.money'));

        } elseif($type == 0) {

            $orders = $orders->where('a.parent_id',$parentId)->where('a.raised_money',"<",DB::raw('b.money'));

        } elseif($type == 4) {

            $orders = $orders->whereRaw(DB::raw("find_in_set({$parentId},id_tree)"));

        } elseif($type == 2) {

            $orders = $orders->where('a.parent_id',$parentId);
        }


        $orders = $orders->select("a.*",'b.title','b.money','b.begin_time','b.end_time')->get();


        foreach($orders as $order)
        {
            $order->begin_time          = str_replace("-","/",substr($order->begin_time,0,11));
            $order->end_time            = str_replace("-","/",substr($order->end_time,0,11));
        }

        //获取总的数据
        $data       = [
            'orders'    => $orders,
            'typeId'    => $typeId
        ];
        return view('www/zc-admin/child-order',$data);
    }



    /*
     * 获得订单类型数量
     * */
    private function get_order_type_numbers($typeId)
    {

        $total = DB::table('666_order as a')
            ->leftJoin('666_activity as b','b.activity_id','=','a.activity_id')
            ->where('b.type_id',$typeId)
            ->where('a.deleted_at')
            ->where('b.delete_at')
            ->count();
        //dd($total);
        $finish = DB::table('666_order as a')
            ->leftJoin('666_activity as b','b.activity_id','=','a.activity_id')
            ->where('b.type_id',$typeId)
            ->where('a.deleted_at')
            ->where('b.delete_at')
            ->where("a.raised_money",">=",DB::raw('b.money'))
            ->count();

        return ['total'=>$total,'finish'=>$finish];
    }

    public function hand_order(Request $request){
        $orderId    = $request->input('orderId');
        DB::table('666_order')->where('id',$orderId)->update(['hand_status'=>1]);
        return redirect()->back();

    }


    public function activity(Request $request)
    {

        $this->check_login($request);
        $typeId     = $request->input('typeId');
        $manager    = $request->input('manager','');
        $title      = $request->input('title','');

        $activitys  = DB::table('666_activity')->where('type_id',$typeId)->where('delete_at');


        $activitys->where(function($db)use($manager,$title){


            if($title)
            {
                $db->where('title','like',"%{$title}%");

            }
            if($manager)
            {
                $db->orWhere('manager','like',"%{$manager}%");
            }
        });
        $activitys  = $activitys->paginate(10);

        foreach($activitys as $act)
        {
            $count = DB::table('666_order')
                ->where('activity_id',$act->activity_id)
                ->where('raised_money',">=",$act->money)
                ->where('deleted_at')
                ->count();
            $act->order_finish_num = $count;
        }

        $numbers    = $this->get_order_type_numbers($typeId);

        $data       = [
            'activitys' => $activitys,
            'typeId'    => $typeId,
            'finish'    => $numbers['finish'],
            'total'     => $numbers['total']
        ];
        return view('www/zc-admin/activity',$data);
    }


    /**
     * 添加活动页面
     * */
    public function new_activity(Request $request)
    {

        $this->check_login($request);
        $activityId = $request->input('activityId',0);
        $model      = new Active666Model();

        if($activityId> 0)
        {
            $activityInfo   = $model->get_activity_info($activityId);
            $typeId         = $activityInfo->type_id;

        } else {

            $typeId         = $request->input('typeId');
            $activityInfo   = new \stdClass();
            $activityInfo->activity_id      = 0;
            $activityInfo->title            = "";
            $activityInfo->share_title      = "";
            $activityInfo->share_img        = "";
            $activityInfo->manager          = "";
            $activityInfo->manager_img      = "";
            $activityInfo->money            = "";
            $activityInfo->begin_time       = "";
            $activityInfo->end_time         = "";
            $activityInfo->share_desc       = "";
            $activityInfo->ad_imgs          = [];
            $activityInfo->detail_info      =[['content'=>"",],["content"=>""]];
        }

        //return [$activityInfo];
        $data   = [
            'typeId'    =>  $typeId,
            'act'       =>  $activityInfo
        ];

        return view('www/zc-admin/new-activity',$data);
    }





    /**
     * 添加活动
     * */
    public function add_activity(Request $request){

        $this->check_login($request);
        $path   = 'www/zc666/upload/';
        $detail = [];
        $detailContent  = $request->input('detail');
        foreach($request->input('d_title') as $key => $t)
        {
            $detail[$key]   = ['title'=>$t,'content'=>$detailContent[$key]];
        }

        $detail     = \GuzzleHttp\json_encode($detail);

        //$data       = $request->except(['ad','manager_img','share_img','_token','detail','d_title']);
        $data       = [
            'begin_time'    => $request->input('begin_time'),
            'end_time'      => $request->input('end_time'),
            'manager'       => $request->input('manager'),
            'money'         => $request->input('money'),
            'share_desc'    => $request->input('share_desc'),
            'share_title'   => $request->input('share_title'),
            'title'         => $request->input('title'),
            'type_id'       => $request->input('type_id')
        ];

        if($request->file('share_img'))
        {
            $shareImg   = $request->file('share_img')->store($path,'public');
            $data['share_img']  = $shareImg;
        }

        if($request->file('manager_img'))
        {
            $managerImg = $request->file('manager_img')->store($path, 'public');
            $data['manager_img']    = $managerImg;
        }

        $ads        = [];
        if($request->file('ad'))
        {
            foreach($request->file('ad') as $ad)
            {
                $img = $ad->store($path,'public');
                array_push($ads,$img);
            }
        }
        if($request->adimgs)
        {
            $ads    = array_merge($ads,$request->adimgs);
        }


        $data['ad_imgs']    = \GuzzleHttp\json_encode($ads);
        $data['detail_info']     = $detail;
        $data['updated_at'] = date_time();

        $activityId = $request->input('activityId');
        if($activityId > 0)
        {
            DB::table('666_activity')->where('activity_id',$activityId)->update($data);

        }else{

            $data['created_at'] = date_time();
            DB::table('666_activity')->insert($data);

        }

        return apiData()->notice('操作成功');
    }


    public function del_activity(Request $request)
    {

        $activityId     = $request->input('activityId');
        $date           = date_time();
        $sql = "UPDATE 666_activity SET delete_at = '{$date}' WHERE activity_id = $activityId";
        DB::update($sql);

        return apiData()->notice('删除成功');
    }


    public function refundIndex(Request $request)
    {
        //return
    }



    public function refund_order(Request $request)
    {
        $this->check_login($request);
        $typeId     = $request->input('typeId');
        $wxname     = trim($request->input('wxname',''));
        $title      = trim($request->input('title',''));
       
        $status     = trim($request->input('status','-1'));
        $mobile     = trim($request->input('mobile',''));
        $sort       = $request->input('sort','time');
        $activityId = $request->input('activityId',0);
        $showchild  = $request->input('showchild',0);

        $activities = DB::table('666_activity')->select('activity_id','title')->where('type_id',$typeId)->get();
        $orders     = DB::table('666_order as a')
            ->leftJoin('666_activity as b','b.activity_id','=','a.activity_id')
            ->where('b.delete_at')
            ->where('a.deleted_at')
            ->where('b.type_id',$typeId)
            ->where('a.raised_money',">",0);

        $orders = $orders->where(function($db) use ($wxname,$title,$mobile,$status,$activityId) {

                if($title)
                {
                    $db->orWhere('b.title','like',"%{$title}%");
                }

                if($wxname)
                {
                    $db->orWhere('a.wx_name','like',"%{$wxname}%");
                }


                if($mobile){
                    $db->orWhere('a.mobile','like',"%{$mobile}%");
                }
        });

        if($activityId > 0)
        {
            $orders->where('a.activity_id','=',$activityId);
        }

        if($sort == 'time')
        {
            $orders->orderBy('a.id','desc');
        }else{
            $orders->orderBy('a.raised_money','desc');
        }


        $handStatus = $request->input('handStatus','-1');

        
        $orders->where('a.hand_status',0);

    
        $orders = $orders->select("a.*",'b.title','b.money','b.begin_time','b.end_time')->paginate(50);



        foreach($orders as $order)
        {

            
            $count = 0;
            $finishChild = 0;
            $allNum     = 0;
            

            $order->all_num             = $allNum;
            $order->child_num           = $count;
            $order->child_finished_num  = $finishChild;
            
        }

        $numbers = $this->get_order_type_numbers($typeId);

        //获取总的数据

        $data       = [
            'orders'    => $orders,
            'typeId'    => $typeId,
            'total'     => $numbers['total'],
            'finish'    => $numbers['finish'],
            'activitys' => $activities,

        ];

        return view('www/zc-admin/refund_order',$data);
    }



    /**
     * 退回红包
     * */
    public function refund(Request $request)
    {


        $this->check_login($request);
        $typeId     = $request->input('typeId');    //活动分类
        $wxname     = trim($request->input('wxname',''));
        $title      = trim($request->input('title',''));
        $mobile     = trim($request->input('mobile',''));
        $activityId = $request->input('activityId',0);//活动ID
        


        $orders     = DB::table('666_order as a')
            ->leftJoin('666_activity as b','b.activity_id','=','a.activity_id')
            ->where('b.delete_at')
            ->where('a.deleted_at')
            ->where('b.type_id',$typeId)
            ->where('a.raised_money',">",0)
            ->where('a.hand_status',0)
            ->where('refunded_at');

        $orders = $orders->where(function($db) use ($wxname,$title,$mobile,$activityId) {

                if($title)
                {
                    $db->orWhere('b.title','like',"%{$title}%");
                }

                if($wxname)
                {
                    $db->orWhere('a.wx_name','like',"%{$wxname}%");
                }


                if($mobile){
                    $db->orWhere('a.mobile','like',"%{$mobile}%");
                }
        });


        if($activityId > 0)
        {
            $orders->where('a.activity_id','=',$activityId);
        }

    
        $orders = $orders->select("a.*")->get();


        $wxService  = new WeixinServiceController();
        $wxApp      = $wxService->get_weixin_app();
        $payment    = $wxApp->payment;
        foreach($orders as $order)
        {

            //获取子订单
            $paylogs = DB::table('666_order_pay_log')
            ->where('order_id',$order->id)
            ->where('pay_status',1)
            ->where('refund_status',0)
            ->get();
            

            foreach($paylogs as $log)
            {
                $info       = $payment->refund($log->out_trade_no,$log->id,$log->pay_money*100);
                DB::table('666_order_pay_log')->where('id',$log->id)->update(['refund_status'=>1]);
            }

            DB::table('666_order')->where('id',$order->id)->update(['refunded_at'=>date_time()]);
        }

        return apiData()->set_data('info',$orders)->send();

    }
}
